`timescale 1ns / 1ps
/*
 Copyright 2020 Sean Xiao, jxzsxsp@qq.com
 
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
 
 http://www.apache.org/licenses/LICENSE-2.0
 
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

module yue_clint_top (
    input          sys_clk,

    input          l_clk,

    input  [31:0]  i_sft_int_v,
    input  [31:0]  i_timer_l,
    input  [31:0]  i_timer_h,
           
    output [31:0]  o_timer_l,
    output [31:0]  o_timer_h, 
           
    input  [31:0]  i_tcmp_l,
    input  [31:0]  i_tcmp_h,
           
    input  [1:0]   i_timer_valid,
    input  [31:0]  i_tm_ctrl,

    output         o_mtip,
    output         o_msip,

    input          rst_n
);


reg [7:0] rtc_r = 0;
always @ (posedge l_clk)
rtc_r <= rtc_r + 1;

(* ASYNC_REG = "true" *) reg rtc_sys = 0;
always @ (posedge sys_clk )
rtc_sys <= rtc_r[7];


reg [1:0] rtc_toggle = 0;
always @ (posedge sys_clk or negedge rst_n)
if(!rst_n) rtc_toggle <= 0;
else if(i_tm_ctrl[31])
begin
    rtc_toggle <= {rtc_toggle[0], rtc_sys};
end

wire rtcTick = rtc_toggle[1] ^ rtc_toggle[0];



yue_clint u_yue_clint (
    .sys_clk        ( sys_clk ),

    .i_sft_int_v    ( i_sft_int_v ),
    .i_timer_l      ( i_timer_l ),
    .i_timer_h      ( i_timer_h ),
 
    .o_timer_l      ( o_timer_l ),
    .o_timer_h      ( o_timer_h ), 
 
    .i_tcmp_l       ( i_tcmp_l ),
    .i_tcmp_h       ( i_tcmp_h ),
 
    .i_timer_valid  ( i_timer_valid ),
    .i_tm_ctrl      ( i_tm_ctrl ),
 
    .o_mtip         ( o_mtip ),
    .o_msip         ( o_msip ),
    .i_rtcTick      ( rtcTick ),
 
    .rst_n          ( rst_n )
);

endmodule
